package cloud.lysky.java.on.concurrent.threadpool;

import cloud.lysky.java.on.utils.SleepTools;

import java.sql.Connection;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author luoly
 * @describe
 * @date 2023/3/2 22:43
 **/
// 测试使用wait/notify机制实现的数据库连接池
public class DBPoolTest {
    private static final int POOL_SIZE = 10;
    static ThreadPoolWaitAndNotifyImpl pool = new ThreadPoolWaitAndNotifyImpl(POOL_SIZE);
    //控制器：控制main线程将会等待所有worker结束后才继续执行
    static CountDownLatch end;

    public static void main(String[] args) {
        //线程数量
        int threadCount = 50;
        end = new CountDownLatch(threadCount);
        //模拟每个线程的操作次数
        int count = 1;
        //计数器: 统计可以拿到连接的线程
        AtomicInteger got = new AtomicInteger();
        //计数器: 统计没有拿到连接的线程
        AtomicInteger noGot = new AtomicInteger();
        for (int i = 1; i <= threadCount; i++) {
            Thread thread = new Thread(new Worker(count, got, noGot), "worker_" + i);
            thread.start();
        }
    }


    static class Worker implements Runnable {
        int count;
        AtomicInteger got;
        AtomicInteger noGot;

        public Worker(int count, AtomicInteger got, AtomicInteger noGot) {
            this.count = count;
            this.got = got;
            this.noGot = noGot;
        }

        @Override
        public void run() {
            while (count > 0) {
                try {
                    //从连接池中获取连接，如果1000ms内无法获取到将会返回null
                    //分别统计连接获取的数量got和未获取到的数量noGot
                    Connection connection = pool.fetchConnection(1000);
                    if (connection != null) {
                        /* 模拟该线程使用该连接5秒 */
                        SleepTools.ms(5);
                        pool.releaseConnection(connection);
                        got.incrementAndGet();
                    } else {
                        noGot.incrementAndGet();
                        System.out.println("线程[" + Thread.currentThread().getName() + "]等待超时!");
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    count--;
                }
            }
            end.countDown();
        }
    }
}

